﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DisposableBase.cs" company="MyCoreLib">
//   Copyright (C) 2014 Alexey Evlampiev. All rights reserved.
// </copyright>
// <summary>
//   Defines the DisposableBase type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace MyCoreLib
{
    using System;
    using System.Diagnostics;

    /// <summary>
    /// Common base for disposable classes.
    /// </summary>
    public abstract class DisposableBase : IDisposable
    {
        /// <summary>
        /// True if this instance is disposed and False otherwise.
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        private bool m_disposed;

        /// <summary>
        /// Finalizes an instance of the <see cref="DisposableBase"/> class.
        /// </summary>
        ~DisposableBase()
        {
            Dispose(false);
        }

                /// <summary>
        /// Gets a value indicating whether this object is already disposed.
        /// </summary>
        public bool IsDisposed
        {
            get { return m_disposed; }
        }

                /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }        

        /// <summary>
        /// Throws the <see cref="System.ObjectDisposedException"/> exception if this instance is disposed.
        /// </summary>
        protected void ThrowIfDisposed()
        {
            if (m_disposed)
            {
                throw new ObjectDisposedException(
                    string.Format("Cannot access a {0} disposed object", GetType()));
            }
        }

        /// <summary>
        /// Protected implementation of Dispose pattern. 
        /// </summary>
        /// <param name="disposing">Indicates whether this instance is being disposed.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (m_disposed)
            {
                return;
            }

            m_disposed = true;
        }
    }
}
